package com.kaifamiao.listener;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import java.text.MessageFormat;
import java.util.logging.Logger;

@WebListener
public class SessionAttributeListener implements HttpSessionAttributeListener {
    private Logger logger = Logger.getLogger( this.getClass().getName() );

    // 当在 当前会话 中添加属性后就调用 attributeAdded 方法
    @Override
    public void attributeAdded(HttpSessionBindingEvent event) {
        String name = event.getName();
        Object value = event.getValue();
        logger.info( MessageFormat.format("在会话中添加属性: {0} = {1}" , name , value ) );
    }

    // 当成功替换 当前会话 的属性值时调用 attributeReplaced 方法
    @Override
    public void attributeReplaced(HttpSessionBindingEvent event) {
        HttpSession session = event.getSession();
        // 获得标题替换取值的属性名称
        String name = event.getName();
        // 获得被替换前的属性值
        Object old = event.getValue();
        // 根据属性名获取替换之后的新值
        Object value = session.getAttribute( name );
        String pattern = "将{0}属性的值由{1}替换为{2}" ;
        String message = MessageFormat.format( pattern , name , old , value ) ;
        logger.info( message );
    }

    // 当从 当前会话 中删除属性后就调用 attributeRemoved 方法
    @Override
    public void attributeRemoved(HttpSessionBindingEvent event) {
        String name = event.getName();
        Object value = event.getValue();
        logger.info( MessageFormat.format("删除{0}属性，其取值是{1}" , name , value ) );
    }

}
